

module.exports = function(config){
	var passport = require('passport'),
		LocalStrategy = require('passport-local').Strategy,
		User = require('../models/user');

	var hash = require('../service/pass').hash;

	passport.use(new LocalStrategy({
	    usernameField: 'email',
	    passwordField: 'password'
	  },
		function(username, password, done) {
		    User.findOne({ email: username }, function(err, user) {
			    if (err) { return done(err); }
			    if (!user) {
			        return done(null, false, 'not-exits');//return a message,you can return an object as well
			    }
				hash(password, user.salt, function (err, hash) {
				    if (err) return done(err);
				    //success
				    if (hash == user.hash){
				    	return done(null, user)
				    }else {
				    	return done(null, false, 'wrong-password')
				    }
				});

			});
		  }//end func
	  ));//end passport use

	// Serialized and deserialized methods when got from session
	passport.serializeUser(function(user, done) {
		done(null, user._id);
	});

	// only the user ID is serialized to the session
	passport.deserializeUser(function(_id, done) {
	  User.findById(_id, function(err, user) {
	    done(err, user);
	  });
	});

	return passport;
};
